#include<stdio.h>
#include<wait.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/types.h>
#define MAX 1024
#define ARGC 128
#define SEP " "


void debugPrint(char** argv)
{
  for(int i=0;argv[i];i++)
  {
    printf("%d: %s\n",i,argv[i]);
  }
}

int split(char* commandstr,char* argv[])
{
  assert(commandstr);
  assert(argv);

  argv[0] = strtok(commandstr, SEP);
  if(argv[0] == NULL)
    return -1;
  int i = 1;
  while((argv[i++] = strtok(NULL, SEP)));
  return 0;
}

int main()
{
  while(1)
  {
        char* argv[ARGC]={NULL};
        char commandstr[MAX] = {0};
        printf("[xuqin@hecs-6 minishell]:# ");
  
        //--------------------------------------------------
        //获取命令
       char* ret = fgets(commandstr,sizeof(commandstr),stdin);
       assert(ret);
       (void)ret;//防止在不同的环境下导致不使用ret变量编译器报错，保证程序的可移植性
       commandstr[strlen(commandstr)-1]= 0;     
             
       //--------------------------------------------------
        //解析字符串成命令,以" "分割字符串 
        int a = split(commandstr,argv);
        if(a != 0)
            continue;
        //debugPrint(argv);  
       
        //--------------------------------------------------
        //子进程替换，父进程bash
       
        //简单实现cd
        if(strcmp(argv[0],"cd")==0)
        {
            if(argv[1]!=NULL)
            {
                chdir(argv[1]);
            }
            continue;
        }
        
        pid_t id = fork();
        assert(id >=0);     
       (void)id;

        if(id == 0)
        {
            //子进程
            execvp(argv[0],argv);
            exit(10);
        }

        //bash
        int status =0;
        waitpid(-1,&status,0);

  }
  return 0;
}

